from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, FileResponse, Http404
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django.views.decorators.http import require_http_methods
from django_ratelimit.decorators import ratelimit
from django.contrib.auth.models import User

from loguru import logger
from utils.captcha import captcha
from .forms.account import SignupForm, LoginForm
from .models import Accounts

from django.contrib.auth import login, authenticate, logout


def register(request):
    if request.method == "POST":
        form = SignupForm(request.POST, request.FILES)
        if form.is_valid():
            user = form.save()
            login(request, user)  # 注册后自动登录
            return redirect("profile")
    else:
        form = SignupForm()
    return render(request, "accounts/register.html", {"form": form})


def user_login(request):
    if request.method == "GET":
        # 引用 form
        form = LoginForm()
        # 通过form 生成模板
        return render(request, "accounts/login.html", {"form": form})
    elif request.method == "POST":
        logger.info(f"登录请求参数::: {request.POST}")
        # 接收数据并校验（Form组件）
        form = LoginForm(data=request.POST)
        if not form.is_valid():
            logger.error(f"Invalid error>>>{form.errors.get_json_data()}")
            return JsonResponse(
                {"success": False, "errors": form.errors.get_json_data()}
            )
        # 获取用户登录数据，验证登录
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        logger.debug("verify username", username=username)
        user = authenticate(request, username=username, password=password)
        if not user:
            return JsonResponse(
                {
                    "success": False,
                    "errors": {"login-failed": [{"message": "用户名或密码不正确"}]},
                }
            )
        # 登录成功
        login(request, user)
        return JsonResponse({"success": True, "redirect": reverse("productsHome")})


def sms_login(request):
    # sms_login_resp = BaseResponse()
    # if request.method == 'GET':
    #     form = SmsLoginForm()
    #     return render(request, 'sms_login.html', {'form': form})
    #
    # # 1.手机格式校验
    # form = SmsLoginForm(request.POST)
    # if not form.is_valid():
    #     sms_login_resp.detail = form.errors
    #     logger.error(f'验证不通过:::{form.errors}')
    #     return JsonResponse(sms_login_resp.dict)
    # mobile = form.cleaned_data['mobile']
    # role = form.cleaned_data['role']
    #
    # # 2.短信验证码 + redis 中的验证码 ==> 校验- from中实现
    #
    # logger.debug(f'用户 {mobile} 登录')
    # # 3. 登录成功 + 注册 - 由于后续代码需要使用，所以不在form中实现
    # if role == '1':
    #     logger.error(f'管理员登录')
    #     user_object = models.Administrator.objects.filter(active=1, mobile=mobile).first()
    # else:
    #     logger.debug(f'普通用户登录')
    #     user_object = models.Customer.objects.filter(active=1, mobile=mobile).first()
    # logger.info(f'用户查询结果:::{user_object}')
    # if not user_object:
    #     sms_login_resp.detail = {'mobile': ['手机号不存在']}
    #     return JsonResponse(sms_login_resp.dict)
    # mapping = {'1': 'ADMIN', '2': 'CUSTOMER'}
    # # 4. 校验通过，用户信息写入 session + 进入项目后台
    # request.session[settings.NB_SESSION_KEY] = {'role': mapping[role], 'name': user_object.username,
    #                                             'id': user_object.id}
    # sms_login_resp.status = True
    # sms_login_resp.data = LOGIN_HOME
    return JsonResponse({})


# def sms_send(request):
#     """发送短信"""
#     # 实例响应对象
#     rsp = BaseResponse()
#     # 1.校验手机号
#     form = MobileForm(data=request.POST)
#     if not form.is_valid():
#         rsp.detail = form.errors
#         return JsonResponse(rsp.dict)
#     mobile = form.cleaned_data['mobile']
#     # 验证码保存在rides
#     sms_code = generate_sms_code()
#     try:
#         conn = get_redis_connection('default')
#         conn.set(mobile, sms_code, ex=60)
#     except redis.exceptions.ConnectionError:
#         logger.warning(f'redis connect fail, configs {settings.CACHES}')
#         rsp.detail = {'mobile': ['获取验证码失败!!!']}
#         return JsonResponse(rsp.dict)
#     # 成功后返回
#     rsp.status = True
#     rsp.data = {'code': sms_code}
#     return JsonResponse(rsp.dict)


@login_required
def user_logout(request):
    logout(request)

    return JsonResponse({"redirect_url": reverse("login")})


@ratelimit(key="ip", rate="5/m")
@require_http_methods(["GET"])
def get_captcha(request):
    """获取验证码接口"""
    try:
        result = captcha.generate_captcha()
        return JsonResponse({"status": "success", "data": result})
    except Exception as e:
        logger.error(f"get_captcha error {e}")
        return JsonResponse({"status": "error", "message": str(e)}, status=500)


class UserListAPIView(View):
    def get(self, request):
        # users = Accounts.objects.select_related('accounts').filter(is_active=True).values('id', 'name')
        users = (
            User.objects.select_related("accounts")
            .filter(is_active=True)
            .exclude(username=request.user)
            .all()
            .values("username", "id")
        )
        logger.info("query user sql>>>\n{}", users.query)
        logger.debug("query user result \n {}", users)

        return JsonResponse(list(users), safe=False)


# class UserAvatars(View):
#     """获取用户头像"""
#     content_type_map = {
#         '.jpg': 'image/jpeg',
#         '.jpeg': 'image/jpeg',
#         '.png': 'image/png',
#         '.svg': 'image/svg+xml'
#     }
#
#     def get(self, request, year, month, day, name):
#         logger.debug('get product logo {}', request.path)
#         # 图片路径
#         file = settings.MEDIA_ROOT.joinpath('products', 'logo', year, month, day, name)
#         if not file.exists() and not file.is_file():
#             raise Http404("图片文件不存在")
#         # 获取文件扩展名
#         ext = file.suffix
#         content_type = self.content_type_map.get(ext, 'application/octet-stream')
#
#         # 返回图片响应
#         return FileResponse(
#             open(file, 'rb'),
#             content_type=content_type,  # 根据实际格式调整
#             as_attachment=False  # True 会触发下载
#         )

# # 用户搜索接口
# class UserSearchAPI(ListAPIView):
#     queryset = Account.objects.filter(is_active=True)
#     serializer_class = UserSimpleSerializer
#
#     def filter_queryset(self, queryset):
#         search = self.request.query_params.get('search')
#         if search:
#             return queryset.filter(
#                 Q(name__icontains=search) |
#                 Q(email__icontains=search)
#             )
#         return queryset
